document.addEventListener('DOMContentLoaded', function() {
    // 导航切换
    const calculationNavLink = document.getElementById('calculation-nav-link');
    const databaseNavLink = document.getElementById('database-nav-link');
    const calculationModule = document.getElementById('calculation-module');
    const databaseModule = document.getElementById('database-module');
    
    calculationNavLink.addEventListener('click', function(e) {
        e.preventDefault();
        calculationModule.classList.remove('hidden');
        databaseModule.classList.add('hidden');
        calculationNavLink.classList.add('text-primary', 'border-b-2', 'border-primary');
        databaseNavLink.classList.remove('text-primary', 'border-b-2', 'border-primary');
    });
    
    databaseNavLink.addEventListener('click', function(e) {
        e.preventDefault();
        calculationModule.classList.add('hidden');
        databaseModule.classList.remove('hidden');
        databaseNavLink.classList.add('text-primary', 'border-b-2', 'border-primary');
        calculationNavLink.classList.remove('text-primary', 'border-b-2', 'border-primary');
    });
    
    // 测算步骤导航
    const stepButtons = {
        toStep2: document.getElementById('to-step-2'),
        backToStep1: document.getElementById('back-to-step-1'),
        toStep3: document.getElementById('to-step-3'),
        backToStep2: document.getElementById('back-to-step-2')
    };
    
    const steps = {
        step1: document.getElementById('step-1'),
        step2: document.getElementById('step-2'),
        step3: document.getElementById('step-3')
    };
    
    // 步骤切换函数
    function goToStep(stepNumber) {
        // 隐藏所有步骤
        Object.values(steps).forEach(step => {
            step.classList.add('hidden');
        });
        
        // 显示目标步骤
        document.getElementById(`step-${stepNumber}`).classList.remove('hidden');
        
        // 更新步骤指示器
        document.querySelectorAll('[data-step]').forEach(step => {
            const stepNum = parseInt(step.getAttribute('data-step'));
            step.classList.remove('active-step', 'completed-step');
            
            if (stepNum === stepNumber) {
                step.classList.add('active-step');
            } else if (stepNum < stepNumber) {
                step.classList.add('completed-step');
            }
        });
        
        // 更新连接器
        document.querySelectorAll('[data-connector]').forEach(connector => {
            const [from, to] = connector.getAttribute('data-connector').split('-').map(Number);
            if (from < stepNumber) {
                connector.style.width = '100%';
            } else {
                connector.style.width = '0%';
            }
        });
    }
    
    // 步骤按钮事件
    if (stepButtons.toStep2) {
        stepButtons.toStep2.addEventListener('click', () => goToStep(2));
    }
    if (stepButtons.backToStep1) {
        stepButtons.backToStep1.addEventListener('click', () => goToStep(1));
    }
    if (stepButtons.toStep3) {
        stepButtons.toStep3.addEventListener('click', () => goToStep(3));
    }
    if (stepButtons.backToStep2) {
        stepButtons.backToStep2.addEventListener('click', () => goToStep(2));
    }
    
    // 手风琴效果
    document.querySelectorAll('.accordion-header').forEach(header => {
        header.addEventListener('click', function() {
            const content = this.nextElementSibling;
            const icon = this.querySelector('i');
            
            this.classList.toggle('active');
            
            if (this.classList.contains('active')) {
                content.classList.remove('hidden');
                icon.style.transform = 'rotate(180deg)';
            } else {
                content.classList.add('hidden');
                icon.style.transform = 'rotate(0)';
            }
        });
    });
    
    // 加载测算场景
    loadScenarios();
    
    // 加载数据库连接
    loadDatabaseConnections();
    
    // 加载查询历史
    loadQueryHistory();
    
    // 保存场景按钮事件
    const saveScenarioBtn = document.getElementById('save-scenario');
    if (saveScenarioBtn) {
        saveScenarioBtn.addEventListener('click', saveScenario);
    }
    
    // 新建测算按钮事件
    const newCalculationBtn = document.getElementById('new-calculation-btn');
    if (newCalculationBtn) {
        newCalculationBtn.addEventListener('click', function() {
            document.getElementById('scenario-form').reset();
            document.getElementById('scenario-id').value = '';
        });
    }
    
    // 新建数据库连接按钮事件
    const newConnectionBtn = document.getElementById('new-connection-btn');
    const dbConnectionModal = document.getElementById('db-connection-modal');
    const closeDbModalBtn = document.getElementById('close-db-modal');
    const dbConnectionForm = document.getElementById('db-connection-form');
    
    if (newConnectionBtn && dbConnectionModal) {
        newConnectionBtn.addEventListener('click', function() {
            // 重置表单
            if (dbConnectionForm) {
                dbConnectionForm.reset();
                document.getElementById('connection-id').value = '';
            }
            // 显示模态框
            dbConnectionModal.classList.remove('hidden');
        });
    }
    
    // 关闭模态框事件
    if (closeDbModalBtn && dbConnectionModal) {
        closeDbModalBtn.addEventListener('click', function() {
            dbConnectionModal.classList.add('hidden');
        });
    }
    
    // 点击模态框背景关闭
    if (dbConnectionModal) {
        dbConnectionModal.addEventListener('click', function(e) {
            if (e.target === dbConnectionModal) {
                dbConnectionModal.classList.add('hidden');
            }
        });
    }
    
    // 数据库连接表单提交事件
    if (dbConnectionForm) {
        dbConnectionForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveDbConnection();
        });
    }
    
    // 测试连接按钮事件
    const testConnectionBtn = document.getElementById('test-connection-btn');
    if (testConnectionBtn) {
        testConnectionBtn.addEventListener('click', function() {
            testNewConnection();
        });
    }
    
    // 执行查询按钮事件
    const runQueryBtn = document.getElementById('run-query');
    if (runQueryBtn) {
        runQueryBtn.addEventListener('click', executeQuery);
    }
});

// 加载测算场景
function loadScenarios() {
    fetch('/api/scenarios')
        .then(response => response.json())
        .then(scenarios => {
            const scenariosList = document.getElementById('scenarios-list');
            scenariosList.innerHTML = '';
            
            if (scenarios.length === 0) {
                scenariosList.innerHTML = `
                    <div class="text-center py-10 text-neutral-500">
                        <i class="fa fa-file-text-o text-2xl mb-2"></i>
                        <p>暂无测算场景，请点击"创建新场景"按钮</p>
                    </div>
                `;
                return;
            }
            
            scenarios.forEach(scenario => {
                const scenarioCard = document.createElement('div');
                scenarioCard.className = 'border border-neutral-200 rounded-xl p-4 card-hover-effect';
                scenarioCard.innerHTML = `
                    <div class="flex justify-between items-start">
                        <div>
                            <h5 class="font-medium text-neutral-800">${scenario.name}</h5>
                            <p class="text-sm text-neutral-500 mt-1 line-clamp-2">${scenario.description || '无描述'}</p>
                            <div class="flex items-center mt-3 text-xs text-neutral-500">
                                <span class="bg-neutral-100 px-2 py-0.5 rounded-full mr-2">${getScenarioTypeName(scenario.type)}</span>
                                <span><i class="fa fa-calendar-o mr-1"></i>${new Date(scenario.updated_at).toLocaleString()}</span>
                            </div>
                        </div>
                        <div class="flex space-x-1">
                            <button class="text-neutral-400 hover:text-primary p-1" onclick="editScenario(${scenario.id})" title="编辑">
                                <i class="fa fa-pencil"></i>
                            </button>
                            <button class="text-neutral-400 hover:text-danger p-1" onclick="deleteScenario(${scenario.id})" title="删除">
                                <i class="fa fa-trash-o"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mt-3 flex justify-end">
                        <button class="text-primary hover:text-primary/80 text-sm font-medium" onclick="selectScenario(${scenario.id}, '${escapeHtml(scenario.name)}')">
                            选择此场景 <i class="fa fa-arrow-right ml-1"></i>
                        </button>
                    </div>
                `;
                scenariosList.appendChild(scenarioCard);
            });
        })
        .catch(error => {
            console.error('加载测算场景失败:', error);
            document.getElementById('scenarios-list').innerHTML = `
                <div class="text-center py-10 text-danger">
                    <i class="fa fa-exclamation-circle text-2xl mb-2"></i>
                    <p>加载失败，请刷新页面重试</p>
                </div>
            `;
        });
}

// 获取当前场景ID
function getCurrentScenarioId() {
    // 首先尝试从隐藏字段获取
    const scenarioIdField = document.getElementById('scenario-id');
    if (scenarioIdField && scenarioIdField.value) {
        return scenarioIdField.value;
    }
    
    // 如果没有隐藏字段，尝试从URL获取
    const path = window.location.pathname;
    const match = path.match(/\/scenarios\/(\d+)/);
    return match ? match[1] : null;
}

// 保存测算场景
function saveScenario() {
    const scenarioId = getCurrentScenarioId();
    const name = document.getElementById('scenario-name').value;
    const description = document.getElementById('scenario-desc').value;
    const type = document.getElementById('scenario-type').value;
    const dbConnectionId = document.getElementById('scenario-db').value;
    
    // 简单验证
    if (!name || !type) {
        showNotification('请填写必填字段', 'warning');
        return;
    }
    
    const scenarioData = {
        name,
        description,
        type,
        db_connection_id: dbConnectionId || null
    };
    
    const method = scenarioId ? 'PUT' : 'POST';
    const url = scenarioId ? `/api/scenarios/${scenarioId}` : '/api/scenarios';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(scenarioData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('保存失败');
        }
        return response.json();
    })
    .then(data => {
        showNotification(scenarioId ? '场景更新成功' : '场景创建成功', 'success');
        loadScenarios();
        document.getElementById('scenario-form').reset();
        document.getElementById('scenario-id').value = '';
    })
    .catch(error => {
        console.error('保存场景失败:', error);
        showNotification('保存失败，请重试', 'error');
    });
}

// 加载数据库连接
function loadDatabaseConnections() {
    fetch('/api/connections')
        .then(response => response.json())
        .then(connections => {
            const connectionsTable = document.getElementById('connections-table-body');
            const dbSelect = document.getElementById('db-connection-select');
            const scenarioDbSelect = document.getElementById('scenario-db');
            
            // 清空现有内容
            connectionsTable.innerHTML = '';
            if (dbSelect) dbSelect.innerHTML = '<option value="">选择数据库连接</option>';
            if (scenarioDbSelect) scenarioDbSelect.innerHTML = '<option value="">不关联数据库</option>';
            
            if (connections.length === 0) {
                connectionsTable.innerHTML = `
                    <tr>
                        <td colspan="8" class="px-6 py-10 text-center text-neutral-500">
                            <i class="fa fa-database text-2xl mb-2"></i>
                            <p>暂无数据库连接，请点击"新建连接"按钮</p>
                        </td>
                    </tr>
                `;
                return;
            }
            
            // 填充连接表格
            connections.forEach(conn => {
                const statusClass = 'bg-success/10 text-success'; // 这里简化处理，实际应检测连接状态
                
                const row = document.createElement('tr');
                row.className = 'hover:bg-neutral-50 transition-colors';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <input type="checkbox" class="rounded border-neutral-300 text-primary focus:ring-primary">
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">${conn.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${getDbTypeName(conn.db_type)}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${conn.host}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${conn.port}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${conn.database}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 py-1 text-xs font-semibold rounded-full ${statusClass}">
                            可用
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 mr-3" onclick="testConnection(${conn.id})">测试</button>
                        <button class="text-neutral-600 hover:text-neutral-900 mr-3" onclick="useConnection(${conn.id})">使用</button>
                        <button class="text-danger hover:text-danger/80" onclick="deleteConnection(${conn.id})">删除</button>
                    </td>
                `;
                connectionsTable.appendChild(row);
                
                // 添加到下拉选择框
                if (dbSelect) {
                    const option = document.createElement('option');
                    option.value = conn.id;
                    option.textContent = `${conn.name} (${getDbTypeName(conn.db_type)})`;
                    dbSelect.appendChild(option);
                }
                
                if (scenarioDbSelect) {
                    const option = document.createElement('option');
                    option.value = conn.id;
                    option.textContent = `${conn.name} (${getDbTypeName(conn.db_type)})`;
                    scenarioDbSelect.appendChild(option);
                }
            });
        })
        .catch(error => {
            console.error('加载数据库连接失败:', error);
            document.getElementById('connections-table-body').innerHTML = `
                <tr>
                    <td colspan="8" class="px-6 py-10 text-center text-danger">
                        <i class="fa fa-exclamation-circle text-2xl mb-2"></i>
                        <p>加载失败，请刷新页面重试</p>
                    </td>
                </tr>
            `;
        });
}

// 执行SQL查询
function executeQuery() {
    const connId = document.getElementById('db-connection-select').value;
    const query = document.getElementById('sql-editor').value;
    
    if (!connId) {
        showNotification('请选择数据库连接', 'warning');
        return;
    }
    
    if (!query.trim()) {
        showNotification('请输入SQL查询语句', 'warning');
        return;
    }
    
    const resultContainer = document.getElementById('query-result-container');
    resultContainer.innerHTML = `
        <div class="flex items-center justify-center h-full text-neutral-500">
            <i class="fa fa-spinner fa-spin mr-2"></i> 执行查询中...
        </div>
    `;
    
    fetch('/api/query', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            connection_id: connId,
            query: query
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 显示查询结果
            if (data.data.length === 0) {
                resultContainer.innerHTML = `
                    <div class="flex items-center justify-center h-full text-neutral-500">
                        <i class="fa fa-info-circle mr-2"></i> 查询成功，但未返回任何数据
                    </div>
                `;
            } else {
                // 构建结果表格
                let tableHtml = `
                    <table class="min-w-full divide-y divide-neutral-200">
                        <thead class="bg-neutral-50">
                            <tr>
                `;
                
                // 添加表头
                data.columns.forEach(col => {
                    tableHtml += `<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">${col}</th>`;
                });
                
                tableHtml += `
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-neutral-200">
                `;
                
                // 添加数据行
                data.data.forEach(row => {
                    tableHtml += '<tr>';
                    row.forEach(cell => {
                        tableHtml += `<td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-700">${cell !== null ? escapeHtml(cell.toString()) : ''}</td>`;
                    });
                    tableHtml += '</tr>';
                });
                
                tableHtml += `
                        </tbody>
                    </table>
                `;
                
                resultContainer.innerHTML = tableHtml;
                
                // 显示导出和复制按钮
                document.getElementById('export-result').classList.remove('hidden');
                document.getElementById('copy-result').classList.remove('hidden');
            }
            
            // 更新查询状态
            document.getElementById('query-status').textContent = `查询成功，返回 ${data.data.length} 行数据`;
            showNotification('查询执行成功', 'success');
            
            // 重新加载查询历史
            loadQueryHistory();
        } else {
            resultContainer.innerHTML = `
                <div class="flex items-center justify-center h-full text-danger p-6">
                    <i class="fa fa-exclamation-triangle mr-2"></i>
                    <div>
                        <p class="font-medium">查询执行失败</p>
                        <p class="text-sm mt-1">${data.error}</p>
                    </div>
                </div>
            `;
            showNotification('查询执行失败', 'error');
        }
    })
    .catch(error => {
        console.error('执行查询失败:', error);
        resultContainer.innerHTML = `
            <div class="flex items-center justify-center h-full text-danger">
                <i class="fa fa-exclamation-circle mr-2"></i> 执行查询时发生错误
            </div>
        `;
        showNotification('执行查询时发生错误', 'error');
    });
}

// 加载查询历史
function loadQueryHistory() {
    const historyContainer = document.getElementById('query-history-container');
    
    // 这里应该从API获取真实数据，这里使用模拟数据
    const mockHistory = [
        { id: 1, query: 'SELECT * FROM sales_data LIMIT 10', time: '2023-07-15 14:30:22', success: true },
        { id: 2, query: 'SELECT AVG(price) FROM products WHERE category = "electronics"', time: '2023-07-15 13:45:10', success: true },
        { id: 3, query: 'SELECT * FROM non_existent_table', time: '2023-07-14 09:15:33', success: false }
    ];
    
    historyContainer.innerHTML = '';
    
    if (mockHistory.length === 0) {
        historyContainer.innerHTML = `
            <div class="text-center py-10 text-neutral-500">
                <i class="fa fa-history text-2xl mb-2"></i>
                <p>暂无查询历史记录</p>
            </div>
        `;
        return;
    }
    
    mockHistory.forEach(item => {
        const historyItem = document.createElement('div');
        historyItem.className = `border border-neutral-200 rounded-lg p-3 ${item.success ? '' : 'border-danger/30 bg-danger/5'}`;
        historyItem.innerHTML = `
            <div class="flex justify-between items-start mb-2">
                <div class="text-sm font-medium text-neutral-700 truncate max-w-[80%]">${item.query}</div>
                <div class="flex space-x-1">
                    <button class="text-neutral-400 hover:text-primary text-xs p-1" onclick="loadQueryFromHistory('${escapeHtml(item.query)}')" title="加载查询">
                        <i class="fa fa-pencil"></i>
                    </button>
                    <button class="text-neutral-400 hover:text-danger text-xs p-1" title="删除">
                        <i class="fa fa-trash-o"></i>
                    </button>
                </div>
            </div>
            <div class="flex justify-between items-center text-xs text-neutral-500">
                <span>${item.time}</span>
                <span class="${item.success ? 'text-success' : 'text-danger'}">${item.success ? '成功' : '失败'}</span>
            </div>
        `;
        historyContainer.appendChild(historyItem);
    });
}

// 辅助函数：显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type} show`;
    notification.innerHTML = `
        <div class="flex items-start">
            <i class="fa ${getNotificationIcon(type)} mt-0.5 mr-3"></i>
            <div>
                <p class="font-medium">${type === 'success' ? '成功' : type === 'error' ? '错误' : type === 'warning' ? '警告' : '信息'}</p>
                <p class="text-sm mt-1">${message}</p>
            </div>
            <button class="ml-auto text-neutral-400 hover:text-neutral-600" onclick="this.parentElement.parentElement.remove()">
                <i class="fa fa-times"></i>
            </button>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后自动关闭
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// 辅助函数：获取通知图标
function getNotificationIcon(type) {
    switch(type) {
        case 'success': return 'fa-check-circle';
        case 'error': return 'fa-exclamation-circle';
        case 'warning': return 'fa-exclamation-triangle';
        case 'info': return 'fa-info-circle';
        default: return 'fa-info-circle';
    }
}

// 辅助函数：获取数据库类型名称
function getDbTypeName(dbType) {
    const types = {
        'mysql': 'MySQL',
        'postgresql': 'PostgreSQL',
        'sqlserver': 'SQL Server',
        'sqlite': 'SQLite'
    };
    return types[dbType] || dbType;
}

// 辅助函数：获取场景类型名称
function getScenarioTypeName(type) {
    const types = {
        'sales': '销售预测',
        'investment': '投资回报',
        'market': '市场分析',
        'cost': '成本测算',
        'other': '其他类型'
    };
    return types[type] || type;
}

// 辅助函数：HTML转义
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe.toString()
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
}

// 其他辅助函数（场景选择、编辑、删除等）
function selectScenario(id, name) {
    document.getElementById('current-scenario').textContent = name;
    document.getElementById('scenario-name-display').textContent = name;
    document.getElementById('to-step-2').classList.remove('opacity-50', 'cursor-not-allowed');
    showNotification(`已选择测算场景: ${name}`, 'success');
}

// 保存数据库连接
function saveDbConnection() {
    const connectionId = document.getElementById('connection-id').value;
    const connectionData = {
        name: document.getElementById('connection-name').value,
        db_type: document.getElementById('db-type').value,
        host: document.getElementById('db-host').value,
        port: document.getElementById('db-port').value,
        database: document.getElementById('db-name').value,
        username: document.getElementById('db-username').value,
        password: document.getElementById('db-password').value
    };
    
    // 验证必填字段
    if (!connectionData.name || !connectionData.db_type || !connectionData.host || 
        !connectionData.database || !connectionData.username) {
        showNotification('请填写所有必填字段', 'error');
        return;
    }
    
    // 设置默认端口
    if (!connectionData.port) {
        switch(connectionData.db_type) {
            case 'mysql': connectionData.port = '3306'; break;
            case 'postgresql': connectionData.port = '5432'; break;
            case 'sqlserver': connectionData.port = '1433'; break;
            case 'oracle': connectionData.port = '1521'; break;
            default: connectionData.port = '';
        }
    }
    
    const method = connectionId ? 'PUT' : 'POST';
    const url = connectionId ? `/connections/${connectionId}` : '/connections';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(connectionData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('保存失败');
        }
        return response.json();
    })
    .then(data => {
        showNotification(connectionId ? '连接更新成功' : '连接创建成功', 'success');
        document.getElementById('db-connection-modal').classList.add('hidden');
        loadDatabaseConnections();
    })
    .catch(error => {
        console.error('保存连接失败:', error);
        showNotification('保存失败，请重试', 'error');
    });
}

// 测试新建的数据库连接
function testNewConnection() {
    const connectionData = {
        db_type: document.getElementById('db-type').value,
        host: document.getElementById('db-host').value,
        port: document.getElementById('db-port').value,
        database: document.getElementById('db-name').value,
        username: document.getElementById('db-username').value,
        password: document.getElementById('db-password').value
    };
    
    // 验证必填字段
    if (!connectionData.db_type || !connectionData.host || 
        !connectionData.database || !connectionData.username) {
        showNotification('请填写所有必填字段', 'error');
        return;
    }
    
    // 设置默认端口
    if (!connectionData.port) {
        switch(connectionData.db_type) {
            case 'mysql': connectionData.port = '3306'; break;
            case 'postgresql': connectionData.port = '5432'; break;
            case 'sqlserver': connectionData.port = '1433'; break;
            case 'oracle': connectionData.port = '1521'; break;
            default: connectionData.port = '';
        }
    }
    
    fetch('/connections/test', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(connectionData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('连接测试成功', 'success');
        } else {
            showNotification(`连接测试失败: ${data.error}`, 'error');
        }
    })
    .catch(error => {
        console.error('测试连接失败:', error);
        showNotification('测试连接失败，请检查网络连接', 'error');
    });
}

function editScenario(id) {
    // 这里应该从API获取场景详情并填充表单
    showNotification('编辑场景功能将在这里实现', 'info');
}

function deleteScenario(id) {
    if (confirm('确定要删除这个场景吗？此操作不可撤销。')) {
        // 这里应该调用API删除场景
        loadScenarios(); // 重新加载场景列表
        showNotification('场景已删除', 'info');
    }
}

function testConnection(id) {
    // 这里应该调用API测试连接
    showNotification('正在测试连接...', 'info');
    setTimeout(() => {
        showNotification('连接测试成功', 'success');
    }, 1000);
}

function useConnection(id) {
    // 这里应该设置当前使用的连接
    document.getElementById('db-connection-select').value = id;
    document.getElementById('run-query').classList.remove('opacity-50', 'cursor-not-allowed');
    showNotification('已选择数据库连接', 'success');
}

// 加载场景导入数据列表
function loadScenarioImports(scenarioId) {
    if (!scenarioId) {
        scenarioId = getCurrentScenarioId();
    }
    
    if (!scenarioId) {
        console.error('无法获取场景ID');
        return;
    }
    
    fetch(`/scenarios/${scenarioId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取场景数据失败');
            }
            return response.json();
        })
        .then(scenario => {
            const importsList = document.getElementById('data-imports-list');
            if (!importsList) return;
            
            // 清空现有列表
            importsList.innerHTML = '';
            
            if (scenario.imports && scenario.imports.length > 0) {
                // 显示导入数据列表
                scenario.imports.forEach(importItem => {
                    const importElement = document.createElement('div');
                    importElement.className = 'border border-neutral-200 rounded-lg p-4 mb-3';
                    importElement.innerHTML = `
                        <div class="flex justify-between items-center">
                            <div>
                                <h4 class="font-medium text-neutral-700">${importItem.file_name}</h4>
                                <p class="text-sm text-neutral-500">
                                    ${importItem.record_count} 条记录 | 
                                    ${new Date(importItem.imported_at).toLocaleString()}
                                </p>
                            </div>
                            <button class="view-data-btn px-3 py-1 bg-primary text-white rounded text-sm" 
                                    data-import-id="${importItem.id}">
                                查看数据
                            </button>
                        </div>
                    `;
                    importsList.appendChild(importElement);
                });
                
                // 添加查看数据按钮事件
                document.querySelectorAll('.view-data-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const importId = this.getAttribute('data-import-id');
                        viewImportedData(scenarioId, importId);
                    });
                });
            } else {
                // 显示无数据提示
                importsList.innerHTML = `
                    <div class="text-center py-8 text-neutral-500">
                        <p>暂无导入数据</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('加载导入数据失败', 'error');
        });
}

// 查看导入的数据
function viewImportedData(scenarioId, importId) {
    fetch(`/scenarios/${scenarioId}/imports/${importId}/data`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取导入数据失败');
            }
            return response.json();
        })
        .then(result => {
            // 显示数据预览模态框
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
            modal.id = 'data-preview-modal';
            
            // 构建表格HTML
            let tableHTML = '<table class="min-w-full border border-neutral-200">';
            
            // 表头
            if (result.data && result.data.length > 0) {
                tableHTML += '<thead><tr>';
                Object.keys(result.data[0]).forEach(key => {
                    tableHTML += `<th class="border border-neutral-200 px-4 py-2 bg-neutral-50">${key}</th>`;
                });
                tableHTML += '</tr></thead>';
                
                // 表体
                tableHTML += '<tbody>';
                result.data.forEach(row => {
                    tableHTML += '<tr>';
                    Object.values(row).forEach(value => {
                        tableHTML += `<td class="border border-neutral-200 px-4 py-2">${value !== null ? value : ''}</td>`;
                    });
                    tableHTML += '</tr>';
                });
                tableHTML += '</tbody>';
            }
            
            tableHTML += '</table>';
            
            // 构建模态框内容
            modal.innerHTML = `
                <div class="bg-white rounded-xl shadow-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
                    <div class="p-6 border-b border-neutral-200">
                        <div class="flex justify-between items-center">
                            <h3 class="text-xl font-semibold text-neutral-800">数据预览</h3>
                            <button id="close-data-preview" class="text-neutral-500 hover:text-neutral-700">
                                <i class="fa fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div class="p-6 overflow-x-auto">
                        ${tableHTML}
                    </div>
                    <div class="p-6 border-t border-neutral-200 flex justify-between items-center">
                        <div class="text-sm text-neutral-500">
                            共 ${result.total} 条记录，当前显示第 ${result.page} 页，每页 ${result.per_page} 条
                        </div>
                        <div class="flex space-x-2">
                            <button id="prev-page" class="px-3 py-1 bg-neutral-200 text-neutral-700 rounded ${result.page <= 1 ? 'opacity-50 cursor-not-allowed' : ''}">
                                上一页
                            </button>
                            <button id="next-page" class="px-3 py-1 bg-neutral-200 text-neutral-700 rounded ${result.page >= result.total_pages ? 'opacity-50 cursor-not-allowed' : ''}">
                                下一页
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // 关闭模态框事件
            document.getElementById('close-data-preview').addEventListener('click', function() {
                document.getElementById('data-preview-modal').remove();
            });
            
            // 分页事件
            const prevPageBtn = document.getElementById('prev-page');
            const nextPageBtn = document.getElementById('next-page');
            
            if (prevPageBtn && result.page > 1) {
                prevPageBtn.addEventListener('click', function() {
                    document.getElementById('data-preview-modal').remove();
                    viewImportedData(scenarioId, importId, result.page - 1);
                });
            }
            
            if (nextPageBtn && result.page < result.total_pages) {
                nextPageBtn.addEventListener('click', function() {
                    document.getElementById('data-preview-modal').remove();
                    viewImportedData(scenarioId, importId, result.page + 1);
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('加载数据失败', 'error');
        });
}

function deleteConnection(id) {
    if (confirm('确定要删除这个数据库连接吗？此操作不可撤销。')) {
        // 这里应该调用API删除连接
        loadDatabaseConnections(); // 重新加载连接列表
        showNotification('数据库连接已删除', 'info');
    }
}

function loadQueryFromHistory(query) {
    document.getElementById('sql-editor').value = query;
    showNotification('已加载历史查询', 'info');
}
    